package com.pocketmenu.ui;

import java.util.ArrayList;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.pocketmenu.business.AllOrdersCursorAdapter;
import com.pocketmenu.business.Constants;
import com.pocketmenu.business.OrderItemCursorAdapter;
import com.pocketmenu.persistence.FriendsOrders;
import com.pocketmenu.persistence.Item;
import com.pocketmenu.persistence.ItemDataSource;
import com.pocketmenu.persistence.Order;
import com.pocketmenu.persistence.OrderDataSource;
import com.pocketmenu.persistence.OrderItem;
import com.pocketmenu.persistence.SQLiteHelper;

import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class AllOrdersActivity extends Activity {

    protected boolean waitingForThread = true;
    private ArrayList<ArrayList<OrderItem>> itemsMesa;

    private List<OrderTemp> listIdOrderSelected;
    
    private ArrayList<FriendsOrders> listFriendsOrder;
    
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_orders);
        
        getAllOrders();
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_all_orders, menu);
        return true;
    }        
    
    private void getAllOrders()
    {
    	Thread networkThread2 = new Thread() {
      	    @Override
      	    public void run() {
      	    	
      	    	itemsMesa = new ArrayList<ArrayList<OrderItem>>();
	      	    String anterior="";
	      	    ArrayList<OrderItem> ordenes=new ArrayList<OrderItem>();
	  	    	//request       	    
	      	    String metodo = "masPedidos";	
	      	    SoapObject request= new SoapObject(Constants.namespace, metodo);
	      	    request.addProperty("idRestaurante", Constants.idRestaurant);
	
	      	    //modelo sobre
	      	    SoapSerializationEnvelope sobre= new SoapSerializationEnvelope(SoapEnvelope.VER11);
	      	    sobre.dotNet = true;
	
	      	    sobre.setOutputSoapObject(request);
	
	      	    //transporte
	      	    HttpTransportSE transporte= new HttpTransportSE(Constants.url,10000);	          
	      	    transporte.debug = true;           
	      	    //llamada
	      	    try {
	      	    	transporte.call(Constants.namespace+metodo, sobre);
		   			
		   			//resultado
		   			SoapPrimitive resultado = (SoapPrimitive) sobre.getResponse();
		   			String respuesta=resultado.toString();
					String[] restaurantesWeb = respuesta.split(";");
					
		   			for(int i=0;i<restaurantesWeb.length;i++){
		   				
						String[] restauranteWebActual=restaurantesWeb[i].split("\\*");								
						OrderItem actual=new OrderItem();
						String email=restaurantesWeb[4];
						String nombre= restaurantesWeb[5];
						
						if(i==0){
							anterior=email;
							FriendsOrders fo = new FriendsOrders();
							fo.setFriendName(nombre);							
						}
						
						if(!email.equals(anterior) && i!=0){
							itemsMesa.add(ordenes);
							ordenes=new ArrayList<OrderItem>();
							anterior=email;
							
						}
						actual.setQuantity(Integer.parseInt(restauranteWebActual[1]));
						actual.setIdOrder(Integer.parseInt(restauranteWebActual[2]));
						actual.setIdItem(Integer.parseInt(restauranteWebActual[3]));
						ordenes.add(actual);
					}
		   			
			   		
		   			} catch (Exception e) {
	   					Log.i("App.err " + getClass().getSimpleName(), e.getMessage());
		   				e.printStackTrace();
		   				
		   			}
	      	    waitingForThread = false;
      	    }	      	      
  	    };
  	    networkThread2.start();
  	    
  	    while(waitingForThread)
  	    {  	    	
  	    }
  	    
  	    addOrdersToDatabase();
  	    
    }
    
    private void addOrdersToDatabase()
    {
    	ArrayList<OrderItem> orderItemListTemp = new ArrayList<OrderItem>();
    	int sizeOrderItemTemp, sizeItemsMesaTemp, idOrderTemp;
    	OrderItem orderItemTemp;    	
    	Item itemTemp;
    	
    	OrderDataSource orderDatasource = new OrderDataSource(this);
    	ItemDataSource itemDataSource = new ItemDataSource(this);
    	
    	orderDatasource.open();
    	itemDataSource.open();
    	
    	sizeItemsMesaTemp = itemsMesa.size();    	    	    	
    	
    	for(int i = 0; i < sizeItemsMesaTemp; i++)
    	{    		
    		orderItemListTemp = itemsMesa.get(i);
    		if(orderItemListTemp != null)
    		{
    			
    			
	    		sizeOrderItemTemp = orderItemListTemp.size();
	
	    		if(sizeOrderItemTemp > 0)
	    		{
	    			orderItemTemp = orderItemListTemp.get(0);
	    			
	    			if(orderItemTemp != null)
	    			{
		    			idOrderTemp = orderItemTemp.getIdOrder();
		    			
		    			if(idOrderTemp != Constants.idOrder)
		    			{
				    		for(int j = 0; j < sizeOrderItemTemp; j++)
				    		{
				    			orderItemTemp = orderItemListTemp.get(j);
				    			
				    			if(orderItemTemp != null)		    			
				    			{
				    				itemTemp = itemDataSource.getItem(orderItemTemp.getIdItem());		    				
				    				orderDatasource.addOrderItem(itemTemp.getPrice(), orderItemTemp.getIdItem(), idOrderTemp);				    				
				    			}
				    		}
		    			}
	    			}
	    		}
    		}
    	}
    	
    	itemDataSource.close();    	
    	orderDatasource.close();
    	
    }
    
    private void loadOrderListView(View view)
	{
		//String[] from = new String[]{SQLiteHelper.COLUMN_ID, SQLiteHelper.COLUMN_ITEM_PRICE, SQLiteHelper.COLUMN_ORDER_ITEM_QUANTITY};
        
        //int[] to = new int[]{R.id.tvItemName,R.id.tvItemTotalPrice, R.id.tvItemQuantity};
               
        OrderDataSource datasource = new OrderDataSource(this);
        datasource.open();
                
        Cursor cursor = datasource.getAllOrders();                 
		
    	ListViewItemOnTouchListener touchListener = new ListViewItemOnTouchListener() {
			
			@Override
			public void onSwipe(View v, int action) {
				// TODO Auto-generated method stub				
			}
			
			@Override
			public void onClick(View v) {
				
				LinearLayout parent = (LinearLayout)v.getParent();
		    	
		    	ListView parentListview = (ListView) parent.getParent();
		    	
		    	int index = parentListview.getPositionForView(parent);
		    	
		    	OrderTemp orderTemp = listIdOrderSelected.get(index);		    			    	
		    	
		    	if(orderTemp.selected)		    		
		    		v.setBackgroundColor(0xFFFFFFFF);
		    	else
		    		v.setBackgroundColor(0x88A9F5A9);
						
		    	orderTemp.selected = !orderTemp.selected;
			}
		};
        
        SimpleCursorAdapter adp= new AllOrdersCursorAdapter(this, R.layout.single_order_item, cursor, null, null, touchListener);
        
        ListView listView = (ListView) view.findViewById(R.id.lvCheckItems);   
        
        View footerView = View.inflate(this, R.layout.footer_check, null);       
        
        listView.addFooterView(footerView);
        
        listView.setAdapter(adp);
        datasource.close();	
	
	}
    
    
    private class OrderTemp
    {
    	public int idOrder;
    	public boolean selected;
    }
}
